package com.alkaid.commons.controller;

import com.alkaid.commons.core.ExceptionDefinition;
import com.alkaid.commons.ex.ServiceException;
import com.alkaid.commons.utils.JsonResult;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * @author Kylin
 */
@ControllerAdvice
public abstract class BaseController {

    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleException(Throwable e){
        JsonResult<Void> result = new JsonResult<>();
        result.setCode(ExceptionDefinition.MAP.get(e.getClass()));
        result.setMsg(e.getMessage());
        return result;
    }

    @ExceptionHandler(BindException.class)
    public JsonResult<Void> handleMethodException(BindException e){
        JsonResult<Void> result = new JsonResult<>();
        BindingResult br = e.getBindingResult();
        int length = br.getFieldErrors().size();
        result.setCode(400);
        result.setMsg(br.getFieldErrors().get(length - 1).getDefaultMessage());
        return result;
    }
}